14. Setup a ViewModel Test

L5 P2 A03 Setup A ViewModel Test V2

As you just saw in the video, you'll start writing a test for the addNewTask method in the TasksViewModel:

TasksViewModel.kt

fun addNewTask() {
   _newTaskEvent.value = Event(Unit)
}

Step 1: Make A TaskViewModelTest class

Following the same steps you did for StatisticsUtilTest, create a test file for TasksViewModelTest:

  1. Open up the class you wish to test, in the tasks package, TasksViewModel.
  2. Right click on the class name TasksViewModel -> Generate -> Test.
  3. On the Create Test screen, click OK to accept (no need to change any of the default settings).
  4. On the Choose Destination Directory dialog, choose the test directory.

Step 2: Start Writing the Test

  1. Create a new test called addNewTask_setsNewTaskEvent:

TasksViewModelTest.kt

class TasksViewModelTest {

    @Test
    fun addNewTask_setsNewTaskEvent() {

        // Given a fresh TasksViewModel


        // When adding a new task


        // Then the new task event is triggered

    }

}

Step 3: Use AndroidX Test to get a simulated Android Context

  1. Add the AndroidX test dependencies.
  2. Add the Robolectric dependency.

app/build.gradle

dependencies {
    // Other dependencies

    // AndroidX Test - JVM testing
    testImplementation "androidx.test:core-ktx:$androidXTestCoreVersion"
testImplementation "org.robolectric:robolectric:$robolectricVersion"
"androidx.test.ext:junit-ktx:$androidXTestExtKotlinRunnerVersion"
}
  1. Create a TasksViewModel using ApplicationProvider.getApplicationContext() from the AndroidX test library:

TasksViewModelTest.kt

    @Test
    fun addNewTask_setsNewTaskEvent() {

        // Given a fresh ViewModel
        val tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())

        // When adding a new task
        tasksViewModel.addNewTask()

        // Then the new task event is triggered
        // TODO test LiveData
    }
  1. Add the AndoirdJUnit4 test runner:

TasksViewModelTest.kt

@RunWith(AndroidJUnit4::class)
class TasksViewModelTest {

    @Test
    fun addNewTask_setsNewTaskEvent() {

        // Given a fresh ViewModel
        val tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())

        // When adding a new task
        tasksViewModel.addNewTask()

        // Then the new task event is triggered
        // TODO test LiveData
    }
}
  1. Run your TasksViewModelTest. It should pass. In the output, you'll see Robolectric is running your tests: